import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from "@angular/forms";
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { GroupService } from "../../group/group.service";
import { Observable } from "rxjs/Observable";
import { adSystemApiUrl, AliyunOssOutputUrl } from "../../../../config/api";
import { DisplayService } from "../display.service";
import { ActivatedRoute, Route, Router } from "@angular/router";
import { isInteger } from "@ng-bootstrap/ng-bootstrap/util/util";
import { LocalStorageService } from "../../../lib/service/local-storage.service";

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html',
  styleUrls: ['./view.component.scss'],
  providers: [NzMessageService, GroupService]
})
export class ViewComponent implements OnInit {


  validateForm: FormGroup;
  fileList = [];
  picList = [];
  options = [];
  AliyunOssOutputUrl = AliyunOssOutputUrl;
  adSystemApiUrl = adSystemApiUrl;
  url;

  picSizeInfo;

  submitStatus = false;

  //右侧预览区块
  previewTitle;
  previewsubTitle;
  previewSrc;


  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  checkedGoodsInfo = {};
  page = 1;
  pageSize = 5;
  total;
  status = '上架';
  loading = false;
  currentGoodsPrice = 0;
  comparePriceStatus = false;
  skuStatus = false;
  highPriceSkuId = null;
  ghostData = null;
  randomStatus = false;
  activity_goods_prize;

  type = '';
  image = '';
  id;
  name;
  relationID;
  showcase_id;
  sort;
  data;

  //活动弹窗
  activityModalVisible = false;
  activityList = [];
  activityLoading = false;
  activitiesTotal;
  currentClickActivity = {};
  checkedActivityInfo = {};
  activityClickIndex;
  self = this;


  //卡券弹窗
  couponPage = 1;
  couponPageSize = 5;
  couponModalVisible = false;
  couponList = [];
  couponLoading = false;
  couponsTotal;
  currentClickCoupon = {};
  checkedCouponInfo = {};
  couponKeyWord = '';
  couponClickIndex;

  selectedOption;
  boothNumber;
  loadingData;
  template_id;

  typeText = {
    1: { text: '普通拼团', color: 'rgb(299,112,23)' },
    2: { text: '拉新拼团', color: 'rgb(299,112,23)' },
    3: { text: '抽奖拼团', color: 'rgb(299,112,23)' },
    4: { text: '团长免单', color: 'rgb(299,112,23)' },
  };


  constructor(
    private routeInfo: ActivatedRoute,
    public displayService: DisplayService,
    private fb: FormBuilder,
    private groupService: GroupService,
    private router: Router,
    private confirmServ: NzModalService,
    private _message: NzMessageService,
    private localStorageService: LocalStorageService
  ) { }

  ngOnInit() {
    this.template_id = this.localStorageService.getNowApplet()['template_id'];
    this.routeInfo.params.subscribe(params => {
      if (this.id != params.id) {
        this.showcase_id = params.showcaseId;
        this.id = params.id;
        this.boothNumber = params.boothNumber;
        if (this.displayService.list.length == 0) {
          this.getShowCaseList().then(() => {
            this.displayService.list.map((e, i) => {
              if (e['booth_number'] == this.boothNumber) {
                e['typeOpen'] = true;
                this.displayService.id = this.id;
                this.displayService.name = e['name'];
                this.displayService.showCaseId = e['id'];
                this.displayService.boothNumber = this.boothNumber;
              }
            });
          });
        }
        this.getShowCaseInfo(params.id);
        this.displayService.initInfo(this, this.boothNumber);
      }
    })
  }


  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  //获取展位详情信息
  getShowCaseInfo(id) {
    this.loadingData = true;
    this.displayService.getShowCaseDetailInfo(id).subscribe(res => {
      if (res.code === 2000) {

        this.picList = [];
        this.data = [];
        this.name = res.data.name;
        this.type = res.data.type;
        this.url = res.data.url;
        //  a 产品 页面 卡券 活动
        // b 产品 页面 卡券 活动
        //c 图片
        if(this.boothNumber === 'a' && this.type === 'picture') {
          this.type = this.options[0].value;
        }
        if(this.boothNumber === 'c' && this.type != 'picture') {
          this.type = this.options[0].value;
        }

        if(this.boothNumber === 'b' && this.type === 'picture') {
          this.type = this.options[0].value;
        }
        // if ((this.boothNumber === 'c' || this.boothNumber === 'b') && this.type === 'page') {
        //   this.type = this.options[0].value;
        // }

        if (res.data.image) {
          this.picList.push({ 'src': `${AliyunOssOutputUrl}/${res.data.image}?update=${Date.now()}` });
        }

        this.name = res.data.name;
        this.relationID = res.data.relationID;
        this.sort = res.data.sort;

        // if ((this.type === 'picture' || this.type === 'activity') && res.data['activity']) {
        //   let activity = this.data = res.data['activity'];
        //   let goods = activity['activity_goods'][0];
        //   this.checkedActivityInfo = activity;
        //   this.checkedActivityInfo['type'] = this.typeText[goods['type']];
        //   this.checkedActivityInfo['goodsDetail'] = goods['goods'];
        //   this.loadingData = false;
        // } else if (res.data[this.type]) {
        //   this.data = res.data[this.type];
        //   this.loadingData = false;
        // } else {
        //   this.loadingData = false;
        // }

        if (this.type === 'activity' && res.data['activity']) {
          let activity = this.data = res.data['activity'];
          let goods = activity['activity_goods'][0];
          this.checkedActivityInfo = activity;
          this.checkedActivityInfo['type'] = this.typeText[goods['type']];
          this.checkedActivityInfo['goodsDetail'] = goods['goods'];
          this.loadingData = false;
        } else if (res.data[this.type]) {
          this.data = res.data[this.type];
          this.loadingData = false;
        } else {
          this.loadingData = false;
        }

        console.log(this.data);

      }
    });
  }

  getShowCaseList() {
    return new Promise((resolve, reject) => {
      this.displayService.getShowCaseList(this.template_id).subscribe(res => {
        if (res.code === 2000) {
          this.displayService.list = res.data.data;
          let len = this.displayService.list.length;
          this.displayService.list.map((e, i) => {
            e['typeOpen'] = false;
            e['addShow'] = false;
            e['typeValue'] = '';
            this.displayService.getShowCaseDetailList(e['id']).subscribe(res1 => {
              if (res.code === 2000) {
                len--;
                let detailList = this.displayService.list[i]['detailList'] = res1.data.data;
                detailList.map((e, i) => {
                  e['edit'] = false;
                });
                if (len === 0) {
                  resolve();
                }
              };
            });
          });
        }
      })
    })
  }



  fileChange() {
    if (this.fileList.length == 0 && this.picList.length == 0) {
    } else {
    }
  }

  editShowCaseDetail() {
    this.router.navigate([`member/display/edit/${this.showcase_id}/${this.id}/${this.boothNumber}`]);
  }

  delShowCaseDetail() {
    this.confirmServ.confirm({
      title: '温馨提示',
      content: '<b>您确定要删除这个橱窗吗</b>',
      onOk: () => {
        let matchArr = location.pathname.replace(/\//g, '.').split('.');
        let showCaseId = matchArr[matchArr.length - 3];
        let id = matchArr[matchArr.length - 2];
        let booth = location.pathname[location.pathname.length - 1];

        this.displayService.list.forEach((e, i) => {
          if (e['booth_number'] === booth) {
            this.displayService.delShowCaseDetail(this.id).subscribe(res => {
              if (res.code === 2000) {
                this._message.create('success', '删除成功');
                this.displayService.getCaseDetailList(showCaseId, i + '').then((id) => {
                  if (id) {
                    this.displayService.id = id;
                    this.router.navigate([`member/display/${showCaseId}/${id}/${booth}`]);
                  } else {
                    this.router.navigate([`member/display/add/${showCaseId}/${booth}`]);
                  }
                })
              } else {
                this._message.create('error', res.message);
              }
            })
          }
        });
      },
      onCancel() {
      }
    });

  }


  //切换checked查看商品
  toggleViewActivityGoods() {
    this.checkedActivityInfo['flexable'] = !this.checkedActivityInfo['flexable'];
  }
}
